package cn.bulgat.spring.web.config;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import cn.bulgat.common.id.IIdGenerator;
import cn.bulgat.common.id.snowflake.SnowFlakeFactory;
import cn.bulgat.common.id.snowflake.SnowFlakeLoader;

/**
 * logId转换
 * @author Bulgat
 */
public class LogIdConverter extends ClassicConverter {


    @Override
    public String convert(ILoggingEvent event) {
        String reqLogId = event.getMDCPropertyMap().get("reqLogId");
        if (reqLogId != null && !reqLogId.isEmpty()) {
            return reqLogId;
        }
        String globalLogId = event.getMDCPropertyMap().get("globalLogId");
        if (globalLogId != null && !globalLogId.isEmpty()) {
            return globalLogId;
        }
        IIdGenerator<Long> idGenerator =
                SnowFlakeFactory.getSnowFlakeIdGenerator(SnowFlakeLoader.getDataCenterId(), SnowFlakeLoader.getMachineId());
        return String.valueOf(idGenerator.nextId());
    }
}